package config

import (
	"os"
	"path/filepath"
	"time"

	"github.com/spf13/viper"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"gopkg.in/natefinch/lumberjack.v2"
)

func InitLogger() *zap.SugaredLogger {
	mode := zapcore.DebugLevel
	var core zapcore.Core
	if viper.GetString("environment.mode") != "dev" {
		//mode = zapcore.InfoLevel
		core = zapcore.NewCore(getEncoder(), zapcore.NewMultiWriteSyncer(getWriterSyncer()), mode)
		//core = zapcore.NewCore(getEncoder(), zapcore.NewMultiWriteSyncer(os.Stdout), mode)
	} else {
		core = zapcore.NewCore(getEncoder(), zapcore.NewMultiWriteSyncer(getWriterSyncer(), os.Stdout), mode)
		//core = zapcore.NewCore(getEncoder(), zapcore.NewMultiWriteSyncer(os.Stdout), mode)
	}
	return zap.New(core).Sugar()
}

func getEncoder() zapcore.Encoder {
	encoderConfig := zap.NewProductionEncoderConfig()
	encoderConfig.TimeKey = "time"
	encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder
	encoderConfig.EncodeTime = func(t time.Time, pae zapcore.PrimitiveArrayEncoder) {
		pae.AppendString(t.Local().Format(time.DateTime))
	}
	return zapcore.NewJSONEncoder(encoderConfig)
}

func getWriterSyncer() zapcore.WriteSyncer {
	path := viper.GetString("logger.path")
	if path == "" || len(path) == 0 {
		rootPath, _ := os.Getwd()
		path = rootPath + string(filepath.Separator) + "log"
	}
	path = path + string(filepath.Separator) + time.Now().Format(time.DateOnly) + ".txt"

	lumberjackSyncer := &lumberjack.Logger{
		Filename:   path,
		MaxSize:    viper.GetInt("logger.max-size"),
		MaxBackups: viper.GetInt("logger.max-backups"),
		MaxAge:     viper.GetInt("logger.max-age"),
		Compress:   viper.GetBool("logger.compress"),
	}
	return zapcore.AddSync(lumberjackSyncer)
}
